import { message } from 'antd'
import { useTranslations } from 'next-intl'
import { useCallback, useEffect, useState } from 'react'
import type { Socket } from 'socket.io-client'
import { io } from 'socket.io-client'

function useSocket() {
  const [socket, setSocket] = useState<Socket | null>(null)
  const t = useTranslations()

  const errorHandler = useCallback(
    (err: Error) => {
      message.error(t('socket.connectError', { error: err.message }))
      console.error('Socket连接错误:', {
        message: err.message,
        stack: err.stack,
      })
    },
    [t]
  )

  useEffect(() => {
    const newSocket = io('ws://localhost:3001', {
      transports: ['websocket'],
      reconnection: true,
      reconnectionAttempts: 5,
      reconnectionDelay: 1000,
    })

    newSocket.on('connect', () => {
      setSocket(newSocket)
    })

    newSocket.on('connect_error', errorHandler)

    return () => {
      newSocket.off('connect_error', errorHandler)
      newSocket.disconnect()
    }
  }, [errorHandler])

  return socket
}

export default useSocket
